# coding:utf-8
from numpy.core.numeric import array, reshape
from numpy.numarray.numerictypes import Float64, Int16
from numpy.ma.core import size
from wave import open
from struct import unpack

def wavread(filename, normalize = True):
    win = open(filename, 'r')
    buf = win.readframes(win.getnframes())
    x = array(unpack('%dh' % (len(buf) / win.getsampwidth()), buf), Float64)
    x = reshape(x, [win.getnframes(), win.getnchannels()])
    if normalize:
        x /= 2 ** (win.getsampwidth() * 8 - 1)
    return x, win.getframerate(), win.getsampwidth() * 8

def wavwrite(x, fs, bits, filename, normalize = True):
    win = open(filename, 'w')
    win.setnchannels(int(size(x, 1)))
    win.setsampwidth(int(bits / 8))
    win.setframerate(fs)
    if normalize:
        x *= 2 ** (bits - 1)
    buf = array(x, Int16).tostring()
    win.writeframes(buf)
    win.close()
    